//
//  SEGNewMenuHouseViewModel.m
//  Commom
//
//  Created by 梁学彰 on 2020/6/3.
//

#import "SEGNewMenuHouseViewModel.h"

@interface SEGNewMenuHouseViewModel ()

@end

@implementation SEGNewMenuHouseViewModel
#pragma mark - init
- (instancetype)init {
    if (self = [super init]) {
        [self initData];
    }
    return self;
}

#pragma mark - dealloc
- (void)dealloc {
    NSLog(@"%@ dealloc",NSStringFromClass([self class]));
}

//初始化数据
- (void)initData {
    self.adType = SEGAdvlistType_Lease;
    self.rentalType = SEGRentalSelectTypeHouse;
    self.page = 1;
    SEGQuerydictlistDictlistModel *houseTypeModel = [[SEGQuerydictlistDictlistModel alloc] init];
    houseTypeModel.value = @"0";
    houseTypeModel.name = @"全部";
    houseTypeModel.isSelect = YES;
    
    SEGQuerydictlistDictlistModel *rentalTypeModel =  [[SEGQuerydictlistDictlistModel alloc] init];
    rentalTypeModel.value = @"0";
    rentalTypeModel.name = @"全部";
    rentalTypeModel.isSelect = YES;
    
    SEGRegionListItemModel *regionModel = [SEGRegionListItemModel new];
    regionModel.name = @"全部";
    regionModel.level = @"1";//和市一级
    regionModel.regionId = @"0";
    regionModel.isSelect = YES;
    
    self.regionArray = [@[regionModel] mutableCopy];
    self.houseTypeArr = [@[houseTypeModel] mutableCopy];
    self.saleTypeArr = [@[rentalTypeModel] mutableCopy];
    
    SEGQuerydictlistDictlistModel *carRentalTypeModel =  [[SEGQuerydictlistDictlistModel alloc] init];
    carRentalTypeModel.value = @"0";
    carRentalTypeModel.name = @"全部车位";
    carRentalTypeModel.isSelect = YES;
    
    SEGQuerydictlistDictlistModel *carRentalTypeModel1 =  [[SEGQuerydictlistDictlistModel alloc] init];
    carRentalTypeModel1.value = @"5";
    carRentalTypeModel1.name = @"车位出租";
    
    SEGQuerydictlistDictlistModel *carRentalTypeModel2 =  [[SEGQuerydictlistDictlistModel alloc] init];
    carRentalTypeModel2.value = @"6";
    carRentalTypeModel2.name = @"车位出售";
    self.carRentalTypeArr = [@[carRentalTypeModel,carRentalTypeModel1,carRentalTypeModel2] mutableCopy];
}


#pragma mark - send request
- (RACSignal *)sendAdRequest {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [[SEGAdvlistManager sharedManager] segRequestAdvlistWithPositionType:self.adType completed:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull codeType, NSString * _Nonnull errorMessage) {
            if (isSuccessed) {
                self.adData = [self segAdvertisementWithData:result type:self.adType];
                [subscriber sendNext:nil];
            }
            [subscriber sendCompleted];
        }];
        return nil;
    }];
    return signal;
}

- (RACSignal *)sendLocationRequest {
    RACSignal *locateSignal = [self seg_bdLoc];
    
    RACSignal *regionRequestSignal = [self sendGetRegionIdRequest];
    
    RACSignal *itemRequestSignal = [self sendItemListRequest];
    
    RACSignal *signal = [RACSignal concat:@[locateSignal,regionRequestSignal,itemRequestSignal]];
    
    return signal;
}

- (RACSignal *)seg_bdLoc {
    @weakify(self);
    [[CCLocationManager shareLocation] getUserLocationInfo];
    RACSignal *locateSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [self.locationManager requestLocationWithReGeocode:YES withNetworkState:NO completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
            
            if (error) {
                
                [subscriber sendNext:[NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:error.localizedDescription}]];
            }
            CLAuthorizationStatus authStatus = [CLLocationManager authorizationStatus];
            BOOL isLocationServicesEnabled = [CLLocationManager locationServicesEnabled];//
            BOOL isAuth = (authStatus == kCLAuthorizationStatusAuthorizedWhenInUse || authStatus == kCLAuthorizationStatusAuthorizedAlways);
            if (isLocationServicesEnabled && isAuth) {
                //百度的
                
                BMKLocationReGeocode *rgcData = location.rgcData;
                if (rgcData.cityCode && rgcData.cityCode.length > 0) {
                    //有变化 重新请求展示
                    if(![rgcData.cityCode isEqualToString:self.cityCode]) {
                        //先请求cityId对应的区域Id
                        self.cityCode = rgcData.cityCode;
                    }
                }
            } else if (authStatus == kCLAuthorizationStatusDenied){

                [subscriber sendNext:[NSError errorWithDomain:@"" code:100 userInfo:nil]];
            }
            [subscriber sendCompleted];
        }];
        return nil;
    }];
    
    return locateSignal;
    
}


- (RACSignal *)sendGetRegionIdRequest{
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        if (!self.cityCode) {
            [subscriber sendCompleted];
        }else {
            [self.requestManager requestQueryRegionByCode:self.cityCode Finished:^(id result, NSError *error) {
                NSString* code = [result objectForKey:@"code"];
                if (![code isEqualToString:@"0"]) {
                    [subscriber sendNext:error];
                    return;
                }
                if (code&&[code isKindOfClass:[NSString class]]) {
                    if ([code isEqualToString:@"0"]) {
                        NSArray <SEGRegionListItemModel *> *arr = [result objectForKey:@"data"];
                        if (arr&&[arr isKindOfClass:[NSArray class]]) {
                            //创建数据模型
                            [self configCityModelArrayWithArray:arr];
                            [subscriber sendNext:nil];
                        }
                    }
                }
                [subscriber sendCompleted];
            }];
        }
        return nil;
    }];
    return signal;
}

- (RACSignal *)sendItemListRequest{
    RACSignal *signal;
    if (self.rentalType == SEGRentalSelectTypeHouse) {
        signal = [self sendHouseRequest];
    }else if (self.rentalType == SEGRentalSelectTypeCar) {
        signal = [self sendCarRentalRequest];
    }
    return signal;
}


- (RACSignal *)sendCarRentalRequest {
    
    
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        __block NSString *regionId = nil;
        NSString *carType = nil;
        [self.regionArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(SEGRegionListItemModel *regionModel, NSUInteger idx, BOOL *stop) {
            if (regionModel.isSelect) {
                regionId = regionModel.regionId;
                *stop = YES;
            }
            [regionModel.areaArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(SEGRegionListItemModel * _Nonnull subRegionModel, NSUInteger subIdx, BOOL * _Nonnull subStop) {
                if (subRegionModel.isSelect) {
                    regionId = subRegionModel.regionId;
                    *subStop = YES;
                    *stop = YES;
                }
            }];
        }];
        
        for (SEGQuerydictlistDictlistModel *rentalTypeModel in self.carRentalTypeArr) {
            if (rentalTypeModel.isSelect) {
                carType = rentalTypeModel.value;
                break;
            }
        }
        
        
        
        
        [self.requestManager requestCarRentalListWithPage:self.page regionId:regionId carRentalType:carType Finished:^(id result, NSError *error) {
            
            if (!error) {
                SEGCarRentalListDataModel *model = result[@"data"];
                if ([model isKindOfClass:[SEGCarRentalListDataModel class]]) {
                    if (self.page == 1) {
                        [self.houseListArray removeAllObjects];
                    }
                    if (model.parkingRentalList.count > 0) {
                        [self.houseListArray addObjectsFromArray:model.parkingRentalList];
                    }
                }
            }else {
                if (self.page == 1) {
                    [self.houseListArray removeAllObjects];
                }
                [subscriber sendError:error];
            }
            [subscriber sendCompleted];
        }];
        return nil;
    }];
    return signal;
}


- (RACSignal *)sendHouseRequest{
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        __block NSString *regionId = nil;
        NSString *houseType = nil;
        NSString *rentalType = nil;
        
        [self.regionArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(SEGRegionListItemModel *regionModel, NSUInteger idx, BOOL *stop) {
            if (regionModel.isSelect) {
                regionId = regionModel.regionId;
                *stop = YES;
            }
            [regionModel.areaArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(SEGRegionListItemModel * _Nonnull subRegionModel, NSUInteger subIdx, BOOL * _Nonnull subStop) {
                if (subRegionModel.isSelect) {
                    regionId = subRegionModel.regionId;
                    *subStop = YES;
                    *stop = YES;
                }
            }];
        }];
        
        for (SEGQuerydictlistDictlistModel *houseTypeModel in self.houseTypeArr) {
            if (houseTypeModel.isSelect) {
                houseType = houseTypeModel.value;
                break;
            }
        }
        
        for (SEGQuerydictlistDictlistModel *rentalTypeModel in self.saleTypeArr) {
            if (rentalTypeModel.isSelect) {
                rentalType = rentalTypeModel.value;
                break;
            }
        }
        
        
        [self.requestManager requestRentalListWithPage:self.page regionId:regionId houseType:houseType rentalType:rentalType Finished:^(id result, NSError *error) {
            if (!error) {
                SEGNewRentallistDataModel *model = result[@"data"];
                if ([model isKindOfClass:[SEGNewRentallistDataModel class]]) {
                    if (self.page == 1) {
                        [self.houseListArray removeAllObjects];
                    }
                    if (model.rentalList.count > 0) {
                        [self.houseListArray addObjectsFromArray:model.rentalList];
                    }
                }
            }else {
                if (self.page == 1) {
                    [self.houseListArray removeAllObjects];
                }
                [subscriber sendError:error];
            }
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
    
    return signal;
    
}

- (RACSignal *)sendGetHouseAndSaleTypeRequest {
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [[SEGQuerydictlistManager sharedManager] requestHouseQuerydictlistWithType:@"houseType,rentalType" finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                NSArray *arr = result[@"data"][@"dictList"];
                if (arr&&[arr isKindOfClass:[NSArray class]]) {
                    NSMutableArray *houseTypeArr = [NSMutableArray array];
                    NSMutableArray *rentalTypeArr = [NSMutableArray array];
                    for (NSDictionary *typeDic in arr) {
                        SEGQuerydictlistDictlistModel *model = [SEGQuerydictlistDictlistModel yy_modelWithDictionary:typeDic];
                        if ([model.type isEqualToString:@"houseType"]) [houseTypeArr addObject:model];
                        if ([model.type isEqualToString:@"rentalType"]) [rentalTypeArr addObject:model];
                    }
                    
                    [self.houseTypeArr addObjectsFromArray:houseTypeArr];
                    [self.saleTypeArr addObjectsFromArray:rentalTypeArr];
                    [subscriber sendNext:nil];
                }
            }else {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
            [subscriber sendCompleted];
        }];
        return nil;
    }];
    return signal;
}





#pragma mark - custom delegate

#pragma mark - system delegate

#pragma mark - event response

#pragma mark - private methods
- (SEGAdvertisementViewModel*)segAdvertisementWithData:(NSArray<SEGAdvertismentModel*>*)dt type:(SEGAdvlistType)type {
    SEGAdvertisementViewModel *data = [[SEGAdvertisementViewModel alloc]init];
    data.adSource = dt;
    if (type == SEGAdvlistType_SERVER){
        data.locationShowType = SEGEnumCommunityLocationViewType_Location;
    }
    data.widgetWidth = LYScreenWidth() - 30;
    return data;
}

- (void)configCityModelArrayWithArray:(NSArray *)arr {
    //城市
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"level == %@", @"1"];
    NSArray <SEGRegionListItemModel *> *cityArray = [arr filteredArrayUsingPredicate:predicate];
    //区
    NSPredicate *areaPredicate = [NSPredicate predicateWithFormat:@"level == %@", @"2"];
    NSMutableArray <SEGRegionListItemModel *> *areaArray = [[arr filteredArrayUsingPredicate:areaPredicate] mutableCopy];
    
    SEGRegionListItemModel *cityModel;
    if (cityArray.count > 0) {
        cityModel = cityArray.firstObject;
    }
    if (cityModel) {
        SEGRegionListItemModel *wholeCityModel = [[SEGRegionListItemModel alloc] init];
        wholeCityModel.level = @"2";
        wholeCityModel.name = @"全城";
        wholeCityModel.isSelect = YES;
        wholeCityModel.regionId = cityModel.regionId;
        [areaArray insertObject:wholeCityModel atIndex:0];
        cityModel.areaArray = areaArray;
        self.regionArray.firstObject.isSelect = NO;
        [self.regionArray insertObject:cityModel atIndex:0];
    }
}

#pragma mark - setter and getter
- (SEGAdvertisementViewModel *)adData {
    if (!_adData) {
        _adData = [SEGAdvertisementViewModel new];
        _adData.widgetWidth = LYScreenWidth() - 30;
    }
    return _adData;
}

- (BMKLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[BMKLocationManager alloc] init];
        //设置位置获取超时时间
        _locationManager.locationTimeout = 10;
        //设置获取地址信息超时时间
        _locationManager.reGeocodeTimeout = 10;
    }
    return _locationManager;
}

- (SEGHouseRentalAndSaleRequestManager *)requestManager {
    if (!_requestManager) {
        _requestManager = [[SEGHouseRentalAndSaleRequestManager alloc] init];
    }
    return _requestManager;
}

- (NSMutableArray *)houseListArray {
    if (!_houseListArray) {
        _houseListArray = [NSMutableArray array];
    }
    return _houseListArray;
}
@end
